package com.young.trigger.handler;


import com.young.common.InetTool;

import java.util.ArrayList;
import java.util.List;

/**
 * 管理服务节点状态的上下文
 */
public final class BrokerContext {

    private static final String NIL = "_NIL_";
    private static volatile String master = NIL;

    private static volatile long scp = -1; // snapshot checkpoint 最后一次状态检查点的时间

    private static volatile boolean closed = false;

    private static volatile List<String> BROKERS = new ArrayList<>();

    /**
     * 检测指定值是否为master
     * @param owner
     * @return
     */
    public static boolean isMaster(String owner) {
        return master.equals(owner);
    }

    /**
     * 检测当前ip是否为master
     * @return
     */
    public static boolean isMaster() {
        return master.equals(InetTool.LOCAL_IP);
    }

    public static boolean isSlave(String owner) {
        return !isMaster(owner);
    }

    public static boolean isSlave() {
        return !isMaster(InetTool.LOCAL_IP);
    }

    public static boolean isNull() {
        return master.equals(NIL);
    }

    public static synchronized void master(String owner) {
        master = (owner == null ? NIL : owner);
    }

    public static synchronized void checkpoint(boolean value) {
        if (value) {
            scp = System.currentTimeMillis();
        }
    }

    public static void close() {
        closed = true;
    }

    public static boolean isClosed() {
        return closed;
    }
    /**
     * 检查是否为本地模式，即从最后一次状态检查点到现在是否超过了3秒
     */
    public static boolean isLocal() {
        return System.currentTimeMillis() - scp > 3 * 1000;
    }

    /**
     * 离过期剩余毫秒数
     * @return
     */
    public static long remaining() {
        return 3 * 1000 + scp - System.currentTimeMillis() ;
    }

    /**
     * master是否还在leading
     * @return
     */
    public static boolean isLeading() {
        return !closed && isMaster() && !isLocal() && !Thread.interrupted();
    }

    /**
     * slave是否已经退休
     * @return
     */
    public static boolean isRetired() {
        return closed || isLocal() || Thread.interrupted();
    }

    public static void brokers(List<String> brokers){
        BROKERS = brokers;
    }

    public static List<String> getBrokers(){
        return BROKERS;
    }
}
